<template>
  <div>
    <div id="createCanvas" class="mar-auto" style="width: 800px;">
      <div id="toolBox" style="width: 780px; margin: 10px auto;padding: 10px; background: #FFD;position: relative">
        <!--<div id="createLabel">-->
          <!--<div class="pad">-->
            <!--<input type="text"/>-->
          <!--</div>-->
          <!--<div class="pad"></div>-->
        <!--</div>-->
        <div style="width: 50px; height: 100px; background: #2898E0" id="img1"></div>
        <div style="width: 100px; height: 100px; background: #2898E0" id="img2"></div>
        <div style="width: 50px; height: 50px; background: #2898E0" id="img3"></div>
        <div style="width: 100px; height: 50px; background: #2898E0" id="img4"></div>
        <div style="width: 80px; height: 100px; background: #2898E0" id="img5"></div>
        <div style="width: 50px; height: 80px; background: #2898E0" id="img6"></div>
      </div>
      <div style="height: 500px; width: 800px; margin: 0 auto;background: #f1f1f1" id="canvas"></div>
      <div class="clear-float">
        <el-button class="pull-right mar-top-10" type="primary" @click="submitCanvas()">提交画布</el-button>
      </div>
    </div>
    <div id="showCanvas" class="mar-auto" style="width: 800px;display: none">
      <!--<div class="clear-float">-->
        <!--<el-button class="pull-right mar-bottom-10" type="primary" @click="editCanvas()">编辑画布</el-button>-->
      <!--</div>-->
    </div>
  </div>
</template>

<style>
  #toolBox div {margin: 10px 20px; cursor: pointer;display: inline-block}
  #createLabel {
    background: #fff;
    border: 2px solid #eee;
    width: 240px;
    height: 120px;
  }
  #createLabel .pad {
    padding: 15px;
  }
</style>

<script>
  export default {
    data () {
      return {
        DRAGINFO_PREFIX: 'draginfo',
        graph: null,
        createCanvas: true
      }
    },
    mounted () {
      this.createGraph()
    },
    methods: {
      drawGrid () {
        function GridBackground(graph) {
          this.graph = graph;
          graph.onPropertyChange('viewport', this.update.bind(this));
          graph.onPropertyChange('transform', this.update.bind(this));

          this.canvas = Q.createCanvas(graph.width, graph.height, true);
          this.canvas.style.backgroundColor = '#FFD';
          this.canvas.style.position = 'absolute';
          this.canvas.style.top = '0px';
          this.canvas.style['-webkit-user-select'] = 'none';
          this.canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';

          this.scaleCanvas = Q.createCanvas(graph.width, graph.height, true);
          this.scaleCanvas.style.position = 'absolute';
          this.scaleCanvas.style.top = '0px';
          this.scaleCanvas.style['-webkit-user-select'] = 'none';
          this.scaleCanvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';

          graph.canvasPanel.insertBefore(this.canvas, graph.canvasPanel.firstChild);
          graph.canvasPanel.appendChild(this.scaleCanvas);

          this.update();
        }

        GridBackground.prototype = {
          update: function () {
            let graph = this.graph;
            let canvas = this.canvas;
            let scaleCanvas = this.scaleCanvas;
            graph.callLater(function () {
              canvas.setSize(graph.width, graph.height);
              //canvas.width = canvas.width;//clear canvas  todo: ？？？
              scaleCanvas.setSize(graph.width, graph.height);
              scaleCanvas.width = canvas.width;//clear canvas

              let scale = graph.scale;
              let gap = 50 / scale;
              let currentCell = this.currentCell = 10 * (Math.round(gap / 10) || 1);

              scale = graph.scale * canvas.ratio;
              let bounds = graph.viewportBounds;
              let g = canvas.g;

              g.save();
              this._doTransform(g, scale, bounds);

              g.beginPath();
              let x = bounds.x, y = bounds.y, right = bounds.right, bottom = bounds.bottom;
              if (x % currentCell !== 0) {
                x -= (x % currentCell);
              }
              if (y % currentCell !== 0) {
                y -= (y % currentCell);
              }
              while (x < right) {
                g.moveTo(x, bounds.y);
                g.lineTo(x, bottom);
                x += currentCell;
              }
              while (y < bottom) {
                g.moveTo(bounds.x, y);
                g.lineTo(right, y);
                y += currentCell;
              }

              g.lineWidth = 1 / scale;
              g.strokeStyle = '#CCC';
              g.stroke();

              scaleCanvas.g.save();
              this._doTransform(scaleCanvas.g, scale, bounds);
              this.drawScales(scaleCanvas.g, bounds, scale, scaleCanvas.ratio);
              scaleCanvas.g.restore();

              g.restore();
            }, this);
          },
          _doTransform: function(g, scale, bounds){
            g.translate(-scale * bounds.x, -scale * bounds.y);
            g.scale(scale, scale);
          },
          drawText: function (g, text, x, y, fontSize, textAlign, textBaseline, rotate) {
            fontSize = fontSize || 7;
            g.save();
            let fontScale = 3;
            fontSize *= fontScale;
            g.font = 'normal ' + fontSize + 'px helvetica arial';
            g.fillStyle = '#555';
            g.textAlign = textAlign || 'center';
            g.textBaseline = textBaseline || 'top';
            g.translate(x, y);
            if (rotate) {
              g.rotate(rotate);
            }
            g.scale(1 / fontScale, 1 / fontScale);
            g.fillText(text, 0, 0);
            g.restore();
          },
          drawScales: function (g, bounds, scale, ratio) {
            g.beginPath();

            let scaleLength = 5 * ratio / scale;

            g.moveTo(bounds.x, bounds.y);
            g.lineTo(bounds.right, bounds.y);
            g.moveTo(bounds.x, bounds.y);
            g.lineTo(bounds.x, bounds.bottom);

            g.lineWidth = 5 / scale;
            g.strokeStyle = '#2898E0';
            g.stroke();

            let fontSize = 12 * ratio / scale;

            g.beginPath();
            let x = bounds.x;
            x = this.currentCell * Math.ceil(x / this.currentCell);
            while (x < bounds.right) {
              g.moveTo(x, bounds.y);
              g.lineTo(x, bounds.y + scaleLength + scaleLength);
              this.drawText(g, '' + x | 0, x, bounds.y + scaleLength + scaleLength, fontSize);
              x += this.currentCell;
            }
            let y = bounds.y;
            y = this.currentCell * Math.ceil(y / this.currentCell);
            while (y < bounds.bottom) {
              g.moveTo(bounds.x, y);
              g.lineTo(bounds.x + scaleLength + scaleLength, y);
              this.drawText(g, '' + y | 0, bounds.x + scaleLength + scaleLength, y, fontSize, 'center', 'top', -Math.PI / 6);
              y += this.currentCell;
            }
            g.lineWidth = 1 / scale;
            g.strokeStyle = '#000';
            g.stroke();
          }
        };

        new GridBackground(this.graph);
      },
      createGraph () {
        this.graph = new Q.Graph('canvas');
        this.graph.callLater(function(){this.graph.editable = true}.bind(this));
        this.graph.enableWheelZoom = false;

        this.drawGrid();

        this.graph.onElementCreated = function (element, evt, dragInfo) {
          // console.log(dragInfo)
          Q.Graph.prototype.onElementCreated.call(this, element, evt, dragInfo);
          if (element instanceof Q.Edge) {
            element.setStyle(Q.Styles.ARROW_TO, false);
            return;
          }
          if (element instanceof Q.Text) {
            element.setStyle(Q.Styles.LABEL_RADIUS, 0);
            element.setStyle(Q.Styles.LABEL_BACKGROUND_COLOR, "#2898E0");
            element.setStyle(Q.Styles.LABEL_COLOR, "#FFF");
            element.setStyle(Q.Styles.LABEL_PADDING, new Q.Insets(5, 5));
            element.setStyle(Q.Styles.LABEL_POSITION, Q.Position.CENTER_TOP);
            element.setStyle(Q.Styles.LABEL_ALIGN_POSITION, Q.Position.CENTER_TOP);
            element.setStyle(Q.Styles.LABEL_FONT_SIZE, 16);
            element.setStyle(Q.Styles.LABEL_SIZE, new Q.Size(dragInfo.width, dragInfo.height));
          }
        };

        this.initToolbox();
      },
      onDrag (evt) {
        // console.log(evt.target)
        evt = evt || window.event;
        let dataTransfer = evt.dataTransfer;
        let img = evt.target;
        dataTransfer.setData("text", img.getAttribute(this.DRAGINFO_PREFIX));
      },
      createDNDImage (imgId, title, info) {
        let img = document.getElementById(imgId);
        img.setAttribute("draggable", "true");
        img.setAttribute("title", title);
        info = info || {};
        info.label = info.label || title;
        info.title = title;
        img.setAttribute(this.DRAGINFO_PREFIX, JSON.stringify(info));
        img.ondragstart = this.onDrag;
      },
      initToolbox (){
        this.createDNDImage("img1", "box1", {type: "Text", label: "box1", width: 40, height: 90});
        this.createDNDImage("img2", "box2", {type: "Text", label: "box2", width: 90, height: 90});
        this.createDNDImage("img3", "box3", {type: "Text", label: "box3", width: 40, height: 40});
        this.createDNDImage("img4", "box4", {type: "Text", label: "box4", width: 90, height: 40});
        this.createDNDImage("img5", "box5", {type: "Text", label: "box5", width: 70, height: 90});
        this.createDNDImage("img6", "box6", {type: "Text", label: "box6", width: 40, height: 70});
      },
      notEditable () {
        this.graph.editable = false;
        this.graph.isSelectable = function () {
            return false
        };
        this.graph.isMovable = function () {
            return false
        }
        // this.graph.moveToCenter()

//        let model = this.graph.graphModel;
//        model.forEachByTopoDepthFirstSearch(function(node){
//          // node.movable = false;
//          node.selectable = false;
//        });
      },
      allowEdit () {
        this.graph.editable = true;
        this.graph.movable = true;
        // this.graph.moveToCenter()

        let model = this.graph.graphModel;
        model.forEachByTopoDepthFirstSearch(function(node){
          node.movable = true;
        });
      },
      submitCanvas () {
        this.notEditable();
        let canvas = document.getElementById('canvas');
        canvas.style.background = '#FFF';
        canvas.style.border = '1px solid #888';

        this.createCanvas = false;  // todo： ？？？

        let createCanvas = document.getElementById('createCanvas');
        createCanvas.style.display = 'none';

        let showCanvas = document.getElementById('showCanvas');
        showCanvas.style.display = 'block';
        showCanvas.appendChild(canvas);
        // console.log(this.createCanvas)
      },
      editCanvas () {
        this.allowEdit();
        let canvas = document.getElementById('canvas');
        canvas.style.background = '#f1f1f1';
        canvas.style.border = 'none';

        this.createCanvas = false;  // todo： ？？？

        let createCanvas = document.getElementById('createCanvas');
        createCanvas.style.display = 'block';

        let showCanvas = document.getElementById('showCanvas');
        showCanvas.style.display = 'none';
        console.log(this.createCanvas)
      }
    },
    components: {}
  }
</script>
